﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;


namespace VASJ.Service.Library.Manager
{
    public class RolePermissionManager : BaseManager
    {
        /// <summary>
        /// Init
        /// </summary>
        /// <param name="_ApplicationName"></param>
        public RolePermissionManager(string _ApplicationName)
            : base(_ApplicationName)
        {

        }

        /// <summary>
        /// Check user has role permission
        /// </summary>
        /// <returns></returns>
        public bool IsUserHasRolePermission(string userName, string permissionName)
        {
            // Check user is IsPermitUser
            bool retVal = false;

            PermissionTypeManager ptm = new PermissionTypeManager(this.ApplicationName);
            RoleManager rm = new RoleManager(this.ApplicationName);
            UserManager um = new UserManager(this.ApplicationName);

            try
            {
                string[] roles = rm.GetRolesForUser(userName);
                int permissionID = ptm.GetPermissionID(permissionName);
                Guid userID = um.GetUserID(userName);

                var rp = from it in this.mdb.AHSRolePermissions
                         where it.PermissionID.HasValue && it.PermissionID.Value == permissionID && it.RoleID.HasValue && roles.ToList().Contains(it.AHSAspnetRole.Rolename)
                         select it.ID;

                retVal = (rp != null && rp.Count() > 0);
            }
            catch (Exception ex)
            {
                Logger.Log.ErrorFormat("[" + this.ApplicationName + "] IsUserHasRolePermission error {0}", ex);
            }

            return retVal;
        }
    }
}